package com.zhaolixiang.view.animation13

import android.content.Context
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.*
import java.nio.file.Files.size
import com.zhaolixiang.view.animation13.ListAdapter.ViewHolder
import org.w3c.dom.Text
import android.widget.AbsListView


/**
 * Created by Administrator on 2018/1/1.
 */
class ListAdapter(val lists: List<Drawable>, val length: Int, activity: MainActivity, listView2: ListView) : BaseAdapter() {
    private lateinit var layoutInflater: LayoutInflater
    private lateinit var animation: Animation
    private lateinit var listView:ListView
    private var top = 0
    private var viewPOsition=0
    private var isScrollDown = false

    init {
        layoutInflater = LayoutInflater.from(activity)
        animation = AnimationUtils.loadAnimation(activity, R.anim.bottom_in)
        listView=listView2
        listView.setOnScrollListener(object : AbsListView.OnScrollListener {
            override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
                val firstView = view.getChildAt(0)
                if (firstView != null) {
                    val newTop = firstView.top
                    isScrollDown =firstVisibleItem>viewPOsition|| top > newTop
                    viewPOsition=firstVisibleItem
                    top=newTop
                }
            }

            override fun onScrollStateChanged(view: AbsListView?, scrollState: Int) {
            }

        })


    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView;
        var viewHolder: ViewHolder? = null
        if (convertView != null) {
            viewHolder = convertView.tag as ViewHolder
        } else {
            viewHolder = ViewHolder()
            convertView = layoutInflater.inflate(R.layout.item, null)
            viewHolder.iv_img = convertView.findViewById(R.id.iv_img) as ImageView
            viewHolder.tv_title = convertView.findViewById(R.id.tv_title) as TextView
        }
        convertView!!.tag = viewHolder

        for(i in 0 until listView.childCount){
            val view=listView.getChildAt(i)
            view.clearAnimation()
        }
        if(isScrollDown){
            convertView.startAnimation(animation)
        }
        viewHolder.iv_img.setImageDrawable(lists[position % lists.size])
        viewHolder.tv_title.text = position.toString()
        return convertView
    }

    override fun getItem(position: Int) = lists[length % lists.size]

    override fun getItemId(position: Int) = position.toLong()

    override fun getCount() = length
    inner class ViewHolder {
        public lateinit var iv_img: ImageView
        public lateinit var tv_title: TextView
    }
}